package com.tanguy.user.net.http

import android.content.Context
import cn.sinata.util.DES
import cn.sinata.xldutil_kotlin.net.RRetrofit
import cn.sinata.xldutils_kotlin.data.ResultData
import com.alibaba.sdk.android.oss.OSSClient
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider
import com.alibaba.sdk.android.oss.model.PutObjectRequest
import com.google.gson.JsonObject
import com.tanguy.user.App.Companion.app
import com.tanguy.user.Const
import com.tanguy.user.bean.*
import com.tanguy.user.bean.orde.StationOrderBean
import com.tanguy.user.bean.orde.TripOrder
import com.tanguy.user.bean.station.*
import com.tanguy.user.utlis.TimeUtils
import com.tanguy.user.utlis.extend.loge
import com.tanguy.user.utlis.extend.toTimeString
import io.reactivex.Observable
import io.reactivex.schedulers.Schedulers
import java.io.File


/**
 *
 */
object HttpManager {

    val decodeDes: Boolean = false
    val PAGE_SIZE = 15

    class ParamsBuilder {
        private val sb: StringBuilder = StringBuilder()

        companion object {
            val SPLIT: String = "="
            val AND: String = "&"
            val START: String = "?"
            fun create(): ParamsBuilder {
                return ParamsBuilder()
            }
        }

        fun append(vararg params: Pair<String, Any?>): ParamsBuilder {
            if (params.isNotEmpty()) {
                params.forEach {
                    val value = it.second
                    when (value) {
                        is Int -> append_(it.first, value)
                        is Long -> append_(it.first, value)
                        is CharSequence -> append_(it.first, value)
                        is String -> append_(it.first, value)
                        is Float -> append_(it.first, value)
                        is Double -> append_(it.first, value)
                        is Char -> append_(it.first, value)
                        is Short -> append_(it.first, value)
                        is Boolean -> append_(it.first, value)
                    }
                }
            }
            return this
        }

        private fun append_(key: String, value: Any?) {
            if (!sb.isEmpty()) {
//                if (!sb.contains(START)) {
//                    sb.append(START)
//                } else {
//                }
                sb.append(AND)
            }
            sb.append(key).append(SPLIT).append(value)
        }

        /**
         * DES加密类
         */
        fun build(des: Boolean = true): String {
            val toString = sb.toString()
            loge(toString, 2, ">>>>>>>")
            if (des) {
                return DES.encryptDES(toString)
            } else {
                return toString
            }
        }
    }

    /**
     * OSS上传图片
     */
    fun uploadFile(context: Context, fileUrl: String): Observable<String> {
        val file = File(fileUrl)
        // 明文设置secret的方式建议只在测试时使用，更多鉴权模式请参考后面的`访问控制`章节
        val credentialProvider = OSSPlainTextAKSKCredentialProvider(Const.KEY.OSS_AK, Const.KEY.OSS_AKS)
        val oss = OSSClient(context.applicationContext, Const.KEY.OSS_END_POINT, credentialProvider)
        val objectKey = "tangguy/image/" + System.currentTimeMillis() + "." + file.name.substring(file.name.lastIndexOf(".") + 1)
        // 构造上传请求
        val put = PutObjectRequest(Const.KEY.BUCKET_NAME, objectKey, file.path)
        return Observable.just(oss)
                .observeOn(Schedulers.io())
                .map {
                    it.putObject(put)
                    oss.presignPublicObjectURL(Const.KEY.BUCKET_NAME, objectKey)
                }
    }

    /**
     * 获取短信验证码接口
     * @param type 类型【1：登陆 2:修改密码 3:更换手机 4:司机注册】
     */
    fun sendSmsCode(phone: String, type: Int): Observable<ResultData<Any>> {
        return RRetrofit.instance().create(ApiService::class.java).sendSmsCode(phone, type)
    }

    /**
     * 短信登录
     */
    fun loginBySms(phone: String, code: String): Observable<ResultData<User>> {
        return RRetrofit.instance().create(ApiService::class.java).loginBySms(phone, code)
    }

    /**
     * 密码登录
     */
    fun paswLogin(phone: String, password: String): Observable<ResultData<User>> {
        return RRetrofit.instance().create(ApiService::class.java).paswLogin(phone, password)
    }

    /**
     * 验证验证码
     * @param type 【1：登陆 2:修改密码 3:更换手机 4:司机注册】
     */
    fun yzCode(phone: String, type: Int, code: String): Observable<ResultData<Any>> {
        return RRetrofit.instance().create(ApiService::class.java).yzCode(phone, type, code)
    }

    /**
     *  设置和修改密码
     *
     */
    fun settingPas(id: Int, newpas: String, phone: String = ""): Observable<ResultData<Any>> {
        return RRetrofit.instance().create(ApiService::class.java).settingPas(id, phone, newpas, newpas)
    }

    /**
     *  修改绑定手机
     *
     */
    fun replacePhone(oldPhone: String, newPhone: String): Observable<ResultData<Any>> {
        return RRetrofit.instance().create(ApiService::class.java).replacePhone(app.user.userId, oldPhone, newPhone)
    }

    /**
     *  修改用户信息
     *
     */
    fun updateInfo(id: Int, headImg: String = "", name: String = "", autograph: String = "", sex: Int? = null): Observable<ResultData<Any>> {
        return RRetrofit.instance().create(ApiService::class.java).updateInfo(id, headImg, name, autograph, sex)
    }

    /**
     *  我的钱包
     *
     */
    fun getMyMoney(money: Double, id: Int = app.user.userId): Observable<ResultData<JsonObject>> {
        return RRetrofit.instance().create(ApiService::class.java).getMyMoney(id, money)
    }

    /**
     *  获取充值记录
     *
     */
    fun getRechareCord(id: Int, page: Int): Observable<ResultData<ArrayList<RechargeRecord>>> {
        return RRetrofit.instance().create(ApiService::class.java).getRechareCord(id, page, PAGE_SIZE)
    }

    /**
     *  我的优惠券列表
     *
     */
    fun getCouponsList(state: Int, page: Int, id: Int = app.user.userId): Observable<ResultData<ArrayList<CouponsBean>>> {
        return RRetrofit.instance().create(ApiService::class.java).getCouponsList(id, state, page, PAGE_SIZE)
    }

    /**
     *  获取司机评价
     *
     */
    fun getDriverEvaList(page: Int, id: Int = app.user.userId): Observable<ResultData<ArrayList<EvaluateDriver>>> {
        return RRetrofit.instance().create(ApiService::class.java).getDriverEvaList(id, page, PAGE_SIZE)
    }

    /**
     *  获取酒店评价
     *
     */
    fun getHotelEvaList(page: Int, id: Int = app.user.userId): Observable<ResultData<ArrayList<EvaluateHotel>>> {
        return RRetrofit.instance().create(ApiService::class.java).getHotelEvaList(id, page, PAGE_SIZE)
    }

    /**
     *  获得车辆品牌
     *
     */
    fun getBrandList(): Observable<ResultData<ArrayList<CarBrandBean>>> {
        return RRetrofit.instance().create(ApiService::class.java).getBrandList()
    }

    /**
     * 获得车辆类型
     */
    fun getModelList(id: Int): Observable<ResultData<ArrayList<CarModelBean>>> {
        return RRetrofit.instance().create(ApiService::class.java).getModelList(id.toString())
    }

    /**
     *  获得开通省份
     *
     */
    fun getProvinceList(): Observable<ResultData<ArrayList<ProvinceBean>>> {
        return RRetrofit.instance().create(ApiService::class.java).getProvinceList()
    }

    /**
     * 获得开通城市
     */
    fun getCityList(code: String): Observable<ResultData<ArrayList<CityBean>>> {
        return RRetrofit.instance().create(ApiService::class.java).getCityList(code)
    }

    /**
     * 获得酒店类型
     */
    fun getHotelType(): Observable<ResultData<HotelTypeBean>> {
        return RRetrofit.instance().create(ApiService::class.java).getHotelType()
    }

    /**
     * 意见反馈
     */
    fun feedBack(content: String): Observable<ResultData<Any>> {
        return RRetrofit.instance().create(ApiService::class.java).feedBack(app.user.userId, content)
    }


    /**
     * 获得高德webApi 地区
     */
    fun getDistrict(): Observable<JsonObject> {
        return RRetrofit.instance().create_gaode(ApiService::class.java).getDistrict()
    }

    /**
     * 获得高德webApi 输入提示
     */
    fun inputtips(keywords: String, city: String): Observable<JsonObject> {
        return RRetrofit.instance().create_gaode(ApiService::class.java).inputtips(keywords, city)
    }

    /**
     * 司机加盟
     */
    fun driverLeague(driverRegister: DriverRegister): Observable<ResultData<Any>> {
        return RRetrofit.instance().create(ApiService::class.java).driverLeague(
                driverRegister.name
                , driverRegister.sex
                , driverRegister.idcard
                , driverRegister.drivage
                , driverRegister.licenceUrl
                , driverRegister.modelId
                , driverRegister.color
                , driverRegister.plate
                , driverRegister.careful
                , driverRegister.travelUrl
                , driverRegister.insuranceUrl
                , driverRegister.peoplecarUrl
                , app.user.userId
        )
    }

    /**
     * 酒店加盟
     */
    fun hotelLeague(hotelRegister: HotelRegister): Observable<ResultData<Any>> {
        return RRetrofit.instance().create(ApiService::class.java).hotelLeague(
                hotelRegister.name
                , hotelRegister.cityCode
                , hotelRegister.featureid
                , hotelRegister.typeid
                , hotelRegister.hotelAddr
                , hotelRegister.lon
                , hotelRegister.lat
                , hotelRegister.people
                , hotelRegister.phone
                , hotelRegister.showimgUrl
                , hotelRegister.businImgUrl
                , hotelRegister.specialImgUrl
                , hotelRegister.healthImgUrl
                , hotelRegister.fireImgUrl
        )
    }

    /**
     * 出行首页
     */
    fun getTravelPage(id: Int): Observable<ResultData<HomeBean>> {
        return RRetrofit.instance().create(ApiService::class.java).getTravelPage(1, PAGE_SIZE, id)
    }

    /**
     * 推荐有礼
     */
    fun getRecommend(): Observable<ResultData<RecommendBean>> {
        return RRetrofit.instance().create(ApiService::class.java).getRecommend(app.user.userId)
    }

    /**
     * 拉取用户信息
     * 注意:没有返回id,需要自己添加
     */
    fun getUserinfo(id: Int): Observable<ResultData<User>> {
        return RRetrofit.instance().create(ApiService::class.java).getUserinfo(id)
    }

    /**
     * 输入出发地(获取这个城市开通的站点)
     */
    fun origin(code: String): Observable<ResultData<StationBean>> {
        return RRetrofit.instance().create(ApiService::class.java).origin(code)
    }

    /**
     * 接机/送机/接站/送站
     */
    fun docking(type: Int, code: String): Observable<ResultData<DockingBean>> {
        return RRetrofit.instance().create(ApiService::class.java).docking(type, code)
    }

    /**
     * 出发地-->更换城市
     */
    fun getSiteList(cityId: String): Observable<ResultData<UpCityBean>> {
        return RRetrofit.instance().create(ApiService::class.java).getSiteList(cityId)
    }

    /**
     * 输入目的地 将所有开通的城市返回 用于你们选择城市定位
     */
    fun destination(): Observable<ResultData<ListBean>> {
        return RRetrofit.instance().create(ApiService::class.java).destination()
    }

    /**
     * 接站计算价格
     */
    fun calculate(cockOrderBean: StationOrderBean): Observable<ResultData<JsonObject>> {
        return RRetrofit.instance().create(ApiService::class.java).calculate(cockOrderBean.gradeId, cockOrderBean.siteId, cockOrderBean.boulat, cockOrderBean.boulon, cockOrderBean.userId)
    }

    /**
     * 接站发送订单
     */
    fun dockOrder(cockOrderBean: StationOrderBean): Observable<ResultData<JsonObject>> {
        return RRetrofit.instance().create(ApiService::class.java).dockOrder(
                cockOrderBean.siteId,
                cockOrderBean.userId,
                cockOrderBean.boulat,
                cockOrderBean.boulon,
                cockOrderBean.bourn,
                cockOrderBean.gradeId,
                if (cockOrderBean.bybustime == null) System.currentTimeMillis().toTimeString(TimeUtils.TIME_YYYY_MM_DD_HH_MM_SS) else cockOrderBean.bybustime,
                if (cockOrderBean.ista != "1") "2" else "1",
                if (cockOrderBean.taname.isNullOrEmpty()) "" else cockOrderBean.taname,
                if (cockOrderBean.taphone.isNullOrEmpty()) "" else cockOrderBean.taphone,
                cockOrderBean.totalmoney,
                cockOrderBean.coupId,
                cockOrderBean.offstmoney
        )
    }

    /**
     * 送站发送订单
     */
    fun galconOrder(cockOrderBean: StationOrderBean): Observable<ResultData<JsonObject>> {
        return RRetrofit.instance().create(ApiService::class.java).galconOrder(
                cockOrderBean.siteId,
                cockOrderBean.userId,
                cockOrderBean.boulat,
                cockOrderBean.boulon,
                cockOrderBean.bourn,
                cockOrderBean.gradeId,
                if (cockOrderBean.bybustime == null) System.currentTimeMillis().toTimeString(TimeUtils.TIME_YYYY_MM_DD_HH_MM_SS) else cockOrderBean.bybustime,
                if (cockOrderBean.ista != "1") "2" else "1",
                if (cockOrderBean.taname.isNullOrEmpty()) "" else cockOrderBean.taname,
                if (cockOrderBean.taphone.isNullOrEmpty()) "" else cockOrderBean.taphone,
                cockOrderBean.totalmoney,
                cockOrderBean.coupId,
                cockOrderBean.offstmoney,
                cockOrderBean.cityCode

        )
    }

    /**
     * 余额支付
     */
    fun balancePay(orderID: String): Observable<ResultData<JsonObject>> {
        return RRetrofit.instance().create(ApiService::class.java).balancePay(orderID)

    }

    /**
     * 支付宝微信支付
     */
    fun payinfo(type: String, orderId: String): Observable<ResultData<JsonObject>> {
        return RRetrofit.instance().create(ApiService::class.java).payinfo(type, orderId)
    }

    /**
     * 地图获得车型
     */
    fun mapGetCar(cityCode: String): Observable<ResultData<DockingBean>> {
        return RRetrofit.instance().create(ApiService::class.java).mapGetCar(cityCode)
    }

    /**
     * 尝试取消订单
     */
    fun trvalcenlOrder(id: String): Observable<ResultData<JsonObject>> {
        return RRetrofit.instance().create(ApiService::class.java).trvalcenlOrder(id)
    }

    /**
     * 扣钱的取消
     */
    fun trvalcenltow(id: String, kou: String,cenlyy:String,cenlms:String="无"): Observable<ResultData<Any>> {
        return RRetrofit.instance().create(ApiService::class.java).trvalcenltow(id, kou,cenlyy,cenlms)
    }

    /**
     * 获取订单详情
     */
    fun getTravlOrderInfo(orderId: String, type: Int): Observable<ResultData<TripOrder>> {
        return RRetrofit.instance().create(ApiService::class.java).getTravlOrderInfo(orderId, type)
    }

}